# UdpTestClient
#==============
# P. Poliakoff 2015
#
# The UdpTestclient (to be used with the UdpTestServer is intended to test the quality of an IP link
#
# This is limited to IPv4 
#
# Command line arguments
# UdpTestclient serverAddress serverPort PacketSize PacketDelay
#
# The log file: 
# date time packetcounter packet size missing packet_counter
#
#

import socket
import sys
from datetime import datetime
#==========================================================
def string2Port(portString):
    try:
        retval=int(portString)
        if(retval<0) | (retval>0xFFFF):
            raise ValueError
    except:
        sys.exit("Invalid Port value: \""+portString+ "\" Port must be between 0 and 65535")
    return retval
 
def buildBuffer(buffersizeString):
    try:
        bufferSize=int(buffersizeString)
        if(bufferSize<0) | (bufferSize>0xFFFF):
            raise ValueError
    except:
        sys.exit("Invalid buffer size value: \""+buffersizeString+ "\"  must be between 0 and 65535")   
    idx=0
    retval=":"
    datatemplate="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    while idx<bufferSize:
        retval+=datatemplate[idx%26]
        idx+=1
    return (retval,bufferSize)
#==========================================================
# main program

if (len(sys.argv)<3) | (len(sys.argv)>4):
    print ("")
    print ("usage: UdpTestClient serverAddress portNumber packetSize packetPerSecond ")
    print("")
    print ("if packetSize is omitted, the packetsize=1000 bytes")
    print ("if packetpersecond is omitted, the max data rate shall be used")
    print ("")
    print ("Example: UdpTestClient 192.168.0.70 9999 1024 50")
    sys.exit("")


clientsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

host=sys.argv[1]
port=string2Port(sys.argv[2])

packetLengthString="1000"
if len(sys.argv)>=3:
    packetLengthString=(sys.argv[3])
(udpbuffer,packetLength)=buildBuffer(packetLengthString)

clientsocket.connect((host,port))
clientsocket.settimeout(2)
print ("Client started. Press CTRL-C to exit")

counter=1
while True:
    clientsocket.sendall(str(counter)+udpbuffer)
    counter+=1
    print (str(datetime.now())+" Sent Packet#: "+str(counter))
    try:
        dataReceived= clientsocket.recv(packetLength+10)
        print (str(datetime.now())+" Received packet#: "+str(dataReceived))
    except socket.timeout:
        print (str(datetime.now())+" Lost packet echo#: "+str(counter))
